package now;

import java.util.ArrayList;
import java.util.List;

/**
 * 用来管理 Socket 对象
 * 实现存储各个 Socket
 *
 * Created by zhangpeng on 2017/2/12.
 */

public class SocketManager {

    private List<ChatToSocket> socketList=new ArrayList<>();

    public static  SocketManager socketManager;

    private SocketManager (){}

    public static SocketManager getInstance(){
        if(socketManager==null){
            synchronized (SocketManager.class){
                if(socketManager==null){
                    socketManager=new SocketManager();
                }
            }
        }
        return socketManager;
    }

    /**
     *  将新创建的 Socket 对象添加到集合中
     * @param socket
     */
    public void addSocket(ChatToSocket socket){
        if(!socketList.contains(socket)){
            socketList.add(socket);
        }
    }

    /**
     * 将其中一个客户端 socketClient 发来的消息发送到其他客户端
     * socketList 其他要接受消息的客户端
     * @param socketClient 发消息的客户端
     * @param messageFromClient 客户端 socketClient 发送的消息
     */
    public void sayToOtherSocket(ChatToSocket socketClient,String messageFromClient){
        for( ChatToSocket socket :socketList){
            if(!socket.equals(socketClient)){
               socket.write(messageFromClient);
            }
        }
    }
}
